package com.dex4d.ui.main.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.widget.TextView;

import com.dex4d.BuildConfig;
import com.dex4d.R;
import com.dex4d.constants.IConstants;
import com.dex4d.core.AppToolBarBaseActivity;
import com.dex4d.core.http.DefaultTransformer;
import com.dex4d.core.http.JsonApiWrapper;
import com.dex4d.core.subscribers.ProgressSubscriber;
import com.dex4d.model.D4DTxLogModel;
import com.dex4d.model.HttpResult;
import com.dex4d.model.RequestMapParam;
import com.dex4d.model.User;
import com.dex4d.ui.main.model.Dex4dTrade;
import com.dex4d.ui.main.model.TradeResult;
import com.dex4d.ui.qr.model.QRResult;
import com.dex4d.utils.BaseUtils;
import com.dex4d.utils.Commons;
import com.dex4d.utils.LogUtils;

import org.web3j.utils.Convert;

import java.util.Collections;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by chengyuchun on 2018/11/22.
 */
public class TradeConfirmActivity extends AppToolBarBaseActivity implements Commons.BUNDLE_KEYS {

    @BindView(R.id.tv_trade_type)
    TextView tv_trade_type;

    @BindView(R.id.tv_trade_amount)
    TextView tv_trade_amount;

    @BindView(R.id.tv_from_label)
    TextView tv_from_label;

    @BindView(R.id.tv_from_address)
    TextView tv_from_address;

    @BindView(R.id.tv_to_label)
    TextView tv_to_label;

    @BindView(R.id.tv_to_address)
    TextView tv_to_address;

    @BindView(R.id.tv_gas_consumption)
    TextView tv_gas_consumption;

    private Dex4dTrade mTrade;
    private int mType;
    private String mD4DAmount;
    private String mCoinAmount; //除了D4D的token数量,买入、再投资、提现、转账等使用

    @Override
    protected void initToolbar() {
        showBackView();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_trade_confirm;
    }

    @Override
    protected void initVariables() {
        final Bundle bundle = getIntent().getExtras();
        mType = bundle.getInt(TRADE_TYPE);
        String poolSymbol = bundle.getString(POOL_SYMBOL);
        mD4DAmount = bundle.getString(D4D_AMOUNT);
        mCoinAmount = bundle.getString(COIN_AMOUNT);
        final String gas = bundle.getString(GAS_CONSUMPTION);

        //设置交易类，  购买/再投资的情况特殊，设置coinAmount,tokenAmount用于写入日志
        mTrade = new Dex4dTrade(this, poolSymbol);
        mTrade.setTokenAmount(Convert.toWei(TextUtils.isEmpty(mD4DAmount)? "0":mD4DAmount, Convert.Unit.ETHER).toBigInteger().toString());
        mTrade.setCoinAmount(Convert.toWei(TextUtils.isEmpty(mCoinAmount)? "0":mCoinAmount, Convert.Unit.ETHER).toBigInteger().toString());

        if(mType == TradeResult.FLAG_BUY || mType == TradeResult.FLAG_REINVEST){
            //购买、再投资
            tv_trade_type.setText(getString(R.string.d4d_confirm_send_amount));
            tv_trade_amount.setText(mCoinAmount
                    + " " + poolSymbol.toUpperCase());

            //设置dealer,token合约地址，approve时用到
            mTrade.setSpenderAddress(bundle.getString(DEALER_CONTRACT_ADDRESS));
            mTrade.setTokenContractAddress(bundle.getString(TOKEN_CONTRACT_ADDRESS));
            tv_from_address.setText(BaseUtils.formatTxHash(User.getInstance().getAddress()));
            tv_to_address.setText(BaseUtils.formatTxHash(BuildConfig.CONTRACT_DEX4D_PROTOCOL));
        }else if(mType == TradeResult.FLAG_SELL || mType == TradeResult.FLAG_SWAP){
            tv_trade_type.setText(getString(R.string.d4d_confirm_sell_amount));
            tv_trade_amount.setText(mD4DAmount + " D4D");
            tv_from_address.setText(BaseUtils.formatTxHash(User.getInstance().getAddress()));
            tv_to_address.setText(BaseUtils.formatTxHash(BuildConfig.CONTRACT_DEX4D_PROTOCOL));
        }else if(mType == TradeResult.FLAG_WITHDRAW){
            tv_trade_type.setText(getString(R.string.d4d_confirm_send_amount));
            tv_trade_amount.setText(mCoinAmount + " "+getIntent().getStringExtra(WITHDRAW_SYMBOL).toUpperCase());
            tv_from_address.setText(BaseUtils.formatTxHash(User.getInstance().getAddress()));
            tv_to_address.setText(BaseUtils.formatTxHash(BuildConfig.CONTRACT_DEX4D_PROTOCOL));
        }else if(mType == TradeResult.FLAG_BUY_REFERRAL || mType == TradeResult.FLAG_BUY_SWAP){
            tv_trade_type.setText(getString(R.string.d4d_confirm_send_amount));
            tv_trade_amount.setText(mCoinAmount + " ETH");
            tv_from_address.setText(BaseUtils.formatTxHash(User.getInstance().getAddress()));
            tv_to_address.setText(BaseUtils.formatTxHash(BuildConfig.CONTRACT_DEX4D_PROTOCOL));
        }else if(mType == TradeResult.FLAG_TRANSFER){
            //转账
            tv_trade_type.setText(getString(R.string.d4d_confirm_send_amount));
            tv_from_label.setText(getString(R.string.d4d_confirm_send_from));
            tv_to_label.setText(getString(R.string.d4d_confirm_send_to));
            tv_trade_amount.setText(mCoinAmount + " "+getIntent().getStringExtra(TO_SYMBOL).toUpperCase());
            tv_from_address.setText(BaseUtils.formatTxHash(User.getInstance().getAddress()));
            tv_to_address.setText(BaseUtils.formatTxHash(getIntent().getStringExtra(TO_ADDRESS)));
        }

        tv_gas_consumption.setText(gas + " ETH");


        mTrade.setOnTradeListener(new Dex4dTrade.OnTradeListener() {
            @Override
            public void success(TradeResult result) {
                //写入日志
                writeTxLog(result.txLogModel);

                bundle.putString(TRANS_HASH,result.getHash());
                openActivity(TradeDoneActivity.class,bundle);
            }

            @Override
            public void error(TradeResult result) {

            }
        });

        //转账回调
        mTrade.setTransferListener(new Dex4dTrade.OnTransferListener() {
            @Override
            public void success(QRResult result) {
                bundle.putString(TRANS_HASH,BaseUtils.formatTxHash(result.txhash));
                openActivity(TradeDoneActivity.class,bundle);
            }

            @Override
            public void error(QRResult result) {

            }
        });
    }

    @Override
    protected void loadData() {

    }

    @OnClick(R.id.btn_confirm)
    public void onConfirmClick() {
        if (mType == TradeResult.FLAG_BUY || mType == TradeResult.FLAG_REINVEST) {
//            String coinAmountInWei = Convert.toWei(mCoinAmount,Convert.Unit.ETHER).toBigInteger().toString();
//            //购买需要设置coinAmount,因为购买的接口方法中需要使用
//            mTrade.setCoinAmount(coinAmountInWei);
            //以太坊购买
            if (TextUtils.equals(mTrade.getSymbol(), Dex4dTrade.ETH)) {
                mTrade.buy(mTrade.getCoinAmount(), BuildConfig.ADDRESS_X0);
            }
            //其他代币购买
            else {
                mTrade.approve(mTrade.getCoinAmount());
            }
        } else if(mType == TradeResult.FLAG_SELL) {
            //卖出
            mTrade.sell(mD4DAmount);
        } else if(mType == TradeResult.FLAG_SWAP) {
            //对倒
            String toSymbol = getIntent().getStringExtra(TO_SYMBOL);
            mTrade.swap(toSymbol,mD4DAmount);
        } else if(mType == TradeResult.FLAG_WITHDRAW){
            //提现
            String withdrawSymbol = getIntent().getStringExtra(WITHDRAW_SYMBOL);
            mTrade.withdraw(withdrawSymbol,mCoinAmount);
        }else if(mType == TradeResult.FLAG_BUY_REFERRAL){
            //购买推荐权限
            mTrade.buyReferral("0.5",getIntent().getStringExtra(REFERRAL_ALIAS));
        }else if(mType == TradeResult.FLAG_BUY_SWAP){
            //购买对倒权限
            mTrade.buyArbitrage("1");
        }else if(mType == TradeResult.FLAG_TRANSFER){
            //转账
            String toAddress = getIntent().getStringExtra(TO_ADDRESS);
            mTrade.setSymbol(getIntent().getStringExtra(TO_SYMBOL));
            mTrade.setTokenContractAddress(getIntent().getStringExtra(TOKEN_CONTRACT_ADDRESS));
            mTrade.setAssetBalance(getIntent().getStringExtra(ASSET_BALANCE));
            mTrade.send(toAddress, mCoinAmount);
        }
    }

    @OnClick(R.id.btn_reject)
    public void onRejectClick() {
       finish();
    }

    private void writeTxLog(D4DTxLogModel d4DTxLogModel){
        final RequestMapParam<D4DTxLogModel> requestMapParam = new RequestMapParam<D4DTxLogModel>();
        requestMapParam.setId(1);
        requestMapParam.setJsonrpc(IConstants.JSON_RPC_VERSION);
        requestMapParam.setMethod(IConstants.GATEWAY_WRITELOG);
        requestMapParam.setParams(Collections.singletonList(d4DTxLogModel));

        JsonApiWrapper
                .serviceApi()
                .requestByMapParam(requestMapParam)
                .compose(new DefaultTransformer<HttpResult<String>>())  //取网络数据这个函数不能少，这是线程切换
                .subscribe(new ProgressSubscriber<HttpResult<String>>(this, false) {
                    @Override
                    public void onNext(HttpResult<String> result) {
                        LogUtils.d(result.getResult());
                    }
                });
    }
}
